// file: test_file_transfer.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <pthread.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "workCmd.h"  // 确保包含 sendFile_safe / recvFile_safe 定义
#include "enhanceTransfer.h"

#define TEMP_DIR "./temp_recv"
#define BIGFILE_PATH "bigfile"

typedef struct {
    int fd;
    const char* filepath;
} send_arg_t;

typedef struct {
    int fd;
    const char* savedir;
} recv_arg_t;

void* send_thread(void* arg) {
    send_arg_t* sarg = (send_arg_t*)arg;
    sendFile_safe(sarg->fd, sarg->filepath);
    close(sarg->fd);
    return NULL;
}

void* recv_thread(void* arg) {
    recv_arg_t* rarg = (recv_arg_t*)arg;
    recvFile_safe(rarg->fd, rarg->savedir);
    close(rarg->fd);
    return NULL;
}

int compare_files(const char* f1, const char* f2) {
    int fd1 = open(f1, O_RDONLY);
    int fd2 = open(f2, O_RDONLY);
    if(fd1 < 0 || fd2 < 0) return -1;

    char buf1[65536], buf2[65536];
    ssize_t r1, r2;
    int result = 0;

    while(1) {
        r1 = read(fd1, buf1, sizeof(buf1));
        r2 = read(fd2, buf2, sizeof(buf2));
        if(r1 != r2 || memcmp(buf1, buf2, r1) != 0) {
            result = -1;
            break;
        }
        if(r1 == 0) break;
    }

    close(fd1);
    close(fd2);
    return result;
}

int main() {
    // 创建临时接收目录
    mkdir(TEMP_DIR, 0777);

    // 创建 socket pair 代替客户端/服务端通信
    int fds[2];
    if(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) {
        perror("socketpair");
        return 1;
    }

    pthread_t tid_send, tid_recv;

    send_arg_t sarg = { .fd = fds[0], .filepath = BIGFILE_PATH };
    recv_arg_t rarg = { .fd = fds[1], .savedir = TEMP_DIR };

    pthread_create(&tid_recv, NULL, recv_thread, &rarg);
    sleep(1);  // 防止竞态，确保接收端先启动
    pthread_create(&tid_send, NULL, send_thread, &sarg);

    pthread_join(tid_send, NULL);
    pthread_join(tid_recv, NULL);

    // 比较原文件和接收文件
    char recv_path[512];
    snprintf(recv_path, sizeof(recv_path), "%s/%s", TEMP_DIR, "bigfile");

    if(access(recv_path, F_OK) != 0) {
        printf("❌ 接收失败，未找到目标文件\n");
        return 1;
    }

    if(compare_files(BIGFILE_PATH, recv_path) == 0) {
        printf("✅ 文件传输成功，内容一致\n");
        return 0;
    } else {
        printf("❌ 文件内容不一致\n");
        return 1;
    }
}

